import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  TouchableHighlight,
  Image,
  Platform
} from 'react-native';


import CommonViewPagerOne from '../common/CommonViewPagerOne';
import TImage from '../../components/TImage';
import SizeUtils from '../../common/SizeUtils';
import ImageConstants from '../../common/ImageConstants';
import {DateUtils} from '../../utils/Utils';
import CommonStyles from '../../common/CommonStyles';
import Constants from '../../common/Constants';
import Config from '../../config';
import BaseItem from '../common/BaseItem';
import ToastUtils from '../../common/ToastUtils';
import CommonAvatarView from '../common/CommonAvatarView';
import QZ_FollowUser from '../../actions/quanzi/QZ_FollowUser';
import PostRequestLikeAction from '../../actions/post/PostRequestLikeAction';

export default class QuanziPostListItemView extends BaseItem {
  constructor(props) {
    super(props);
    this.state={
      readers_num:this.props.data.readers_num,
      likers_num:this.props.data.likers_num 
    };
  }
  componentWillUpdate(nextProps, nextState) {
    if (nextProps.data.likers_num!==nextState.likers_num) {
      nextState.likers_num=nextProps.data.likers_num||0;
    }
    if (nextProps.data.readers_num!==nextState.readers_num) {
      nextState.readers_num=nextProps.data.readers_num||0;
    }
    if(nextState.needRefresh || nextState.updateByLike) {
      nextState.needRefresh = false;
      nextState.updateByLike = false;
      this.props.refRefresh&&this.props.refRefresh();
      if(nextState.statusText != "") {
        ToastUtils.show(nextState.statusText);
        nextState.statusText = "";
      }
    }
  }
  // componentWillUpdate(nextProps, nextState) {
  //   console.log(nextProps, nextState)
  //   if(nextState.viewStatus == 3 && nextState.isResponeUpdate) {
  //     this.props.refRefresh&&this.props.refRefresh();
  //     return
  //   }
  // }
  render() {
      const keyWord=this.props.keyWord;
      const strat = this.props.data.title&&this.props.data.title.indexOf(keyWord)||'';
      const str1 = this.props.data.title&&this.props.data.title.substr(0,strat)||'';
      const str2 = this.props.data.title&&this.props.data.title.substr(strat,keyWord&&keyWord.length||0)||'';
      const str3 = this.props.data.title&&this.props.data.title.slice(strat+(keyWord&&keyWord.length||0))||'';
    return (
        <TouchableOpacity onPress={()=>{this._onPressItem(this.props.data)}}
          style={{
            paddingTop:SizeUtils.translateDesignHeightToCode(20),
              marginLeft:SizeUtils.translateDesignWidthToCode(20),backgroundColor:"#ffffff",
              marginRight:SizeUtils.translateDesignWidthToCode(20), borderColor:"#eeeeee",
              paddingBottom:SizeUtils.translateDesignHeightToCode(20),
              borderBottomWidth:SizeUtils.translateDesignNumToCode(3)}}>
              {this.props.data.by_user_id?this._renderAvatarView(this.props.data):null}
              {keyWord?
                <Text numberOfLines={2}
                  style={[CommonStyles.primaryText, {fontSize:SizeUtils.translateFontSizeToCode(28),fontWeight:"bold"}]}>
                  {str1}<Text style={{color:'red',fontWeight:'bold'}}>{str2}</Text>{str3}
                </Text>:
                <Text numberOfLines={2}
                  style={[CommonStyles.primaryText, {fontSize:SizeUtils.translateFontSizeToCode(28),fontWeight:"bold"}]}>
                  {this.props.data.title}
                </Text>
              }
             {this._renderImagesBottom(this.props.data)}
           {this.props.comments?this._commentView():this._newsBottomView()}
        </TouchableOpacity>

    )
  }
  _renderAvatarView(data){
    return(
      <View style={{flex:1, flexDirection:"row",
        alignItems: 'center',
        marginBottom:SizeUtils.translateDesignHeightToCode(20),}}>
        {this._renderAvatarContent(data)}
        <View style={{marginLeft:10,flex:1,}}>
          <Text style={[CommonStyles.secondaryText,{color:'#ff9258'}]}>{data.by_name}</Text>
          <Text style={[CommonStyles.secondaryText,{fontSize:11,marginTop:2,}]}>{DateUtils.formatDiffFromServerTime(data.posted_at)}</Text>
        </View>
        {this._renderContentItemTagPer()}
      </View>
    );
  }
  _commentView(){
    return(<View style={{backgroundColor:'#ededed',
        padding:5,
        width:SizeUtils.getWindowSize().width-SizeUtils.translateDesignWidthToCode(40)}}>
        {this._commentListView()}
      </View>)
  }
  _commentListView(){
    var list =[];
    for (var i = 0; i < this.props.comments.length; i++) {
      const item =this.props.comments[i]
      list.push(
        <View key={item.post_id} index={item.post_id} style={{height:SizeUtils.translateDesignHeightToCode(40),
              flexDirection:'row',
            }}>
          <Text style={[CommonStyles.secondaryText,{color:'#3a9bfc'}]}>{item.by_name}:</Text>
          <Text style={[CommonStyles.secondaryText,{color:'#000'}]}>{item.content}</Text>
        </View>
        )
    }
    return list;
  }
  //标签 
  _renderContentItemTagPer() {
    if (this.props.isNoFollow) {return;}
    if (this.props.user_id===this.props.data.by_user_id) {return;}
    return (
      <TouchableOpacity style={{marginLeft:SizeUtils.translateDesignWidthToCode(20),
        backgroundColor:'#fff', borderRadius:SizeUtils.translateDesignNumToCode(10),
        height:SizeUtils.translateDesignHeightToCode(60),
        borderColor:'#ededed', borderWidth:0.5, marginRight:SizeUtils.translateDesignWidthToCode(10),
        flexDirection:"row", justifyContent:"center", alignItems:"center"}}
        onPress={()=>{this.followAction()}}>
        <Text style={{color:this.props.is_follow?'#ff9258':'#999', fontSize:SizeUtils.translateFontSizeToCode(30),
         textAlign:"center",
          marginLeft:SizeUtils.translateDesignWidthToCode(20), marginRight:SizeUtils.translateDesignWidthToCode(20)}}>
         {this.props.is_follow?'已关注':'+ 关注'}
       </Text>
      </TouchableOpacity>
    )
  }
  followAction(){
    new QZ_FollowUser().call(this, {user_id:this.props.data.by_user_id,status:!this.props.is_follow});
  }
  chageBrowse(read,like){
    this.setState({
      readers_num:read,
      likers_num:like
    });
  }
  _sendLikeAction() {
    new PostRequestLikeAction().call(this, this.props.data);
  }
  _renderAvatarContent(data) {
      return (
        <CommonAvatarView avatarUri={data.by_avatar||''} size={90}/>
      )
    }
  _onPressItem(data) {
    if (this.props.isNeedCeck) {
      if(this.props.myData && this.props.myData.is_favorited != 1){
        ToastUtils.show("请先关注该圈子");
        return;
      }
    }
    this.gotoPage(Config.pages.quanzi_post_content,{...data,chageBrowse:this.chageBrowse.bind(this),refRefresh:this.props.refRefresh});
  }
  _renderImagesBottom(data) {
    if(!data.image_urls || data.image_urls.length == 0) {

    }
    else if(data.image_urls.length < 3) {
      return this._renderOneImageBottom(data);
    }
    else if(data.image_urls.length == 3) {
      return (
        <View style={{marginTop:SizeUtils.translateDesignHeightToCode(20), flexDirection:"row",
            width:SizeUtils.translateDesignWidthToCode(750-40), justifyContent:"space-between"}}>
          {this._renderThreeImageBottom(data)}
        </View>
      );
    }
  }
  _renderOneImageBottom(data) {
    return (
      <View style={{marginTop:SizeUtils.translateDesignHeightToCode(20),}}>
        <Image source={{uri:data.image_urls[0]}} style={{width:SizeUtils.getWindowSize().width-SizeUtils.translateDesignWidthToCode(40), height:SizeUtils.getWindowSize().width*0.5}}
          resizeMode={"cover"} />
      </View>
    )
  }
  _renderThreeImageBottom(data) {
    return data.image_urls.map((url, index) => {
      return <TImage key={index} source={{uri:url}} style={{width:((750-70)/3), height:((750-70)/3)}}
        isMini={true} miniSize={"mini200"} resizeMode={"cover"}/>
    })
  }
  _getBottomText(){
    return this.props.data.comments_num +
                " 评论 · 发布时间:" + DateUtils.formatDate2(this.props.data.posted_at);
  }
  _newsBottomView=()=>(
    <View style={{flexDirection:'row',paddingTop:SizeUtils.translateDesignHeightToCode(20),alignItems: 'center',}}>
        <Text
            style={[CommonStyles.secondaryText, {flex:1,fontSize:SizeUtils.translateFontSizeToCode(24),
                }]}>
            {this.props.boardName?'来自':''}<Text style={{color:'#42a1fa'}}>{this.props.boardName}</Text>
        </Text>
        <View style={{flexDirection:'row',alignItems: 'center',justifyContent: 'center',}}>
        <View style={{marginRight:Platform.OS === "android"?10:0,flexDirection:'row',alignItems: 'center',}} onPress={()=>{this._sendLikeAction();}}>
          <TImage source={require("../../../resource/images/home/zan.png")} 
            style={{width:34,height:34,}}/>
          <Text  style={[CommonStyles.secondaryText,{fontSize:SizeUtils.translateFontSizeToCode(24)}]}>
            {' '+this.state.likers_num}
          </Text>
        </View>
        <TImage source={require("../../../resource/images/home/kan.png")} 
            style={{marginLeft:10,width:34,height:34,}}/>
        <Text  style={[CommonStyles.secondaryText,{marginRight:Platform.OS === "android"?10:0,fontSize:SizeUtils.translateFontSizeToCode(24)}]}>
          {' '+this.state.readers_num}
        </Text>
        <TImage source={require("../../../resource/images/home/jianyi.png")} 
            style={{marginLeft:10,width:34,height:34,}}/>
        <Text  style={[CommonStyles.secondaryText,{fontSize:SizeUtils.translateFontSizeToCode(24)}]}>
          {' '+this.props.data.comments_num}
        </Text>
      </View>
    </View> 
  );
   _renderCurrentImages() {
    if(this.props.data.image_urls){
        return (
          <View style={{marginTop:SizeUtils.translateDesignHeightToCode(30)}}>
            <TImage source={{uri:this.props.data.image_urls[0]}} style={{width:660, height:360}}
              resizeMode={"contain"}
              />
          </View>
        )

    }else {
      return(<View></View>)
    }
  }

  _renderCurrentImageItem(imageData, index) {
    this._itemRefs = [];
    // console.log("=============", this._itemRefs);
    return (<TImage source={imageData} style={{width:28, height:28}}/>
      )
  }
}